package com.learn.project2.controller.admin;


import com.learn.project2.bean.MarketAdmin;
import com.learn.project2.config.shiro.MarketToken;
import com.learn.project2.model.vo.admin.auth.AdminInfoVO;
import com.learn.project2.model.vo.admin.auth.AuthInfoVO;
import com.learn.project2.model.vo.admin.auth.AuthLoginVO;
import com.learn.project2.service.admin.auth.AuthService;
import com.learn.project2.utils.AESUtil;
import com.learn.project2.utils.Result;
import com.learn.project2.utils.SecretUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author wxy
 * @version 1.0
 * @description: 后台管理的用户登录
 * @date 2022-01-06 21:53
 */
@RestController
@RequestMapping("admin/auth")
public class AuthController {

    @Autowired
    AuthService authService;


    /**
     * @description: 请求参数简单可以用Map来接收
     * @param:
     * @return:
     * @author wxy
     * @date: 2022-01-06 21-55
     */
    @RequestMapping("login")
    public Result login(@RequestBody Map map, HttpServletRequest request) throws Exception {
        String username = (String) map.get("username");
        String password = (String) map.get("password");

        AuthLoginVO authLoginVO = authService.authLogin(username, password,request);

        return Result.ok(authLoginVO);

    }

    @RequestMapping("info")
    public Result info(String token) {

        Subject subject = SecurityUtils.getSubject();

        MarketAdmin marketAdmin = (MarketAdmin) subject.getPrincipal();

        AuthInfoVO authInfoVO = new AuthInfoVO();
        authInfoVO.setName(marketAdmin.getUsername());
        authInfoVO.setAvatar(marketAdmin.getAvatar());

        List<String> roles = authService.listRoles(marketAdmin);
        authInfoVO.setRoles(roles);
        List<String> perms = authService.listPerms(marketAdmin);
        authInfoVO.setPerms(perms);

        return Result.ok(authInfoVO);

    }


    @PostMapping("logout")
    public Result logout(HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return Result.ok();
    }
}
